/*
 * File:   SynchronizedPriorityQueue.cpp
 * Author: henrya
 *
 * Created on June 27, 2009, 5:02 PM
 */

#include "SynchronizedPriorityQueue.h"
#include <stdlib.h>
#include <stdio.h>

SynchronizedPriorityQueue::~SynchronizedPriorityQueue() {
    pthread_mutex_destroy(&classLock);
}

SynchronizedPriorityQueue::SynchronizedPriorityQueue(unsigned int size, bool isHop) : maxSize(size), isHop(isHop),messagePass(0) {
    if (pthread_mutex_init(&classLock, NULL) != 0) {
        perror("SynchronizedQueue lock initialization");
        exit(1);
    }
}

bool SynchronizedPriorityQueue::push(Message* msg) {
    bool res=false;
    pthread_mutex_lock(&classLock);
    if (queueue.size() < maxSize) {
        static int snCounter(1);
        msg->setSN(snCounter++);
        msg->incHop();
        queueue.push(msg);
        messagePass++;
        res=true;
    }
    pthread_mutex_unlock(&classLock);
    return res;
}

Message* SynchronizedPriorityQueue::pop() {
    Message* res = NULL;
    pthread_mutex_lock(&classLock);
    if (!queueue.empty()) {
        res = queueue.top();
        queueue.pop();
    }
    pthread_mutex_unlock(&classLock);
    return res;
}

unsigned int SynchronizedPriorityQueue::size() {
    unsigned int res(0);
    pthread_mutex_lock(&classLock);
    res = queueue.size();
    pthread_mutex_unlock(&classLock);
    return res;
}

unsigned int SynchronizedPriorityQueue::getMessagePassCount() {
    return messagePass;
}

void SynchronizedPriorityQueue::resetMessagePassCount() {
    messagePass=0;
}
